package com.wdb007.venus.wss.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wdb007.venus.svc.facade.BookgridService;
import com.wdb007.venus.svc.facade.ProcessInstructionService;
import com.wdb007.venus.svc.facade.process.model.ProcessInstructionLogDTO;
import com.wdb007.venus.wss.constants.WsAPPEnum;
import com.wdb007.venus.wss.service.WebSocketServerService;

import io.netty.channel.ChannelHandlerContext;

@Service("bookGridCheckResService")
public class BookGridCheckResService implements WebSocketServerService {

	private static Logger logger = LoggerFactory.getLogger(BookGridCheckResService.class);
	@Autowired
	private BookgridService bookgridService;
	@Autowired
	private ProcessInstructionService processInstructionService;
	@Resource(name="appService")
	private WebSocketServerService appService;
	
	@Override
	public String doService(ChannelHandlerContext ctx, String request) throws Exception {
		JSONObject jsonObj = JSON.parseObject(request);
		String bookGridId = "";
		try {
			bookGridId = jsonObj.getString("bookGridId");
			List<Object> data = Arrays.asList(jsonObj.getJSONArray("data").toArray());
			String pushId = jsonObj.getString("pushId");
			ProcessInstructionLogDTO pi = new ProcessInstructionLogDTO();
			pi.setContent(jsonObj.toJSONString());
			pi.setBookgridCode(bookGridId);
			pi.setInstructionGroupId(Long.valueOf(pushId));
			pi.setStockCount(data.size());
			processInstructionService.checkRes(pi);
			
			logger.info("debug {}: 书格{},data长度:{} 响应内容{}", jsonObj.getString("action"), bookGridId, data.size(), jsonObj.toJSONString());
			List<String> rfids = new ArrayList<String>(data.size());
			for(Object obj : data) {
				rfids.add(((String)obj).toUpperCase());
			}
			String userId = bookgridService.bookGridCheck(bookGridId, rfids);
			if(null != userId) {
				JSONObject jsonApp = new JSONObject();
				jsonApp.put("action", WsAPPEnum.stocktaking_success.name());
				jsonApp.put("userid", userId);
				jsonApp.put("bookgrid_code", bookGridId);
				appService.doService(ctx, jsonApp.toJSONString());
			}
		} catch (Exception e) {
			logger.error("单书格图书盘点"+bookGridId+"异常error", e);
		}
		return null;
	}

}
